<template>
  <HModal title="选择表单" :visible="visible"
          @ok="handleOK" @cancel="close">
    <RowAttribute label="应用名称" :label-width="labelWidth">
      <a-input v-model="appName" placeholder="请输入应用名称"/>
    </RowAttribute>
    <RowAttribute label="单据名称" :label-width="labelWidth">
      <a-input v-model="formName" placeholder="请输入单据名称"/>
    </RowAttribute>
    <HTable @selectChange="selectChange" :dataSource="searchedDataSource" select="single" :configurable="false"
            :columns="columns"/>
  </HModal>
</template>
<script>
import HModal from '@comp/hhd/HModal/HModal.vue';
import HTable from '@comp/hhd/HTable/HTable.vue';
import RowAttribute from '@comp/hhd/layout/RowAttribute.vue';
import {getAction} from '@api/manage';

export default {
  name: 'FormRelationFormSelectorModal',
  components: {
    HTable,
    RowAttribute,
    HModal
  },
  data() {
    return {
      labelWidth: '100px',
      visible: false,
      columns,
      dataSource: [],
      selectedRowKeys: [],
      selectRows: [],
      appName: undefined,
      formName: undefined
    };
  },
  methods: {
    handleOK() {
      if (!this.selectedRowKeys || !this.selectedRowKeys.length) {
        this.$message.warn('请选择单据');
        return;
      }
      this.$emit('ok', this.selectRows[0]);
      this.close();
    },
    selectChange({selectedRowKeys, selectRows}) {
      this.selectRows = selectRows;
      this.selectedRowKeys = selectedRowKeys;
    },
    open() {
      this.visible = true;
      this.initPage();
      this.loadForms();
    },
    loadForms() {
      this.loading = true;
      getAction('/form/designFormDefinition/list', {
        pageSize: 10000,
        form_main: 1,
        _orderBy: 'sort|asc',
      }).then(data => {
        if (data.success) {
          this.dataSource = data.result.records || [];
        } else {
          this.$notification.error({message: data.message, duration: 3});
        }
        this.loading = false;
      }).catch(error => {
        console.log(error);
        this.loading = false;
        this.$notification.error({message: error, duration: 3});
      });
    },
    initPage() {
      this.appName = undefined;
      this.formName = undefined;
      this.selectedRowKeys = [];
      this.selectRows = [];
    },
    close() {
      this.visible = false;
    },
  },
  computed: {
    searchedDataSource() {
      return (this.dataSource || []).filter(item => {
        if(this.appName && item.appName.indexOf(this.appName) === -1) return false
        if(this.formName && item.formName.indexOf(this.formName) === -1) return false
        return true
      });
    },
  }
};

const columns = [
  {
    dataIndex: 'appName',
    title: '应用名称',
  },
  {
    dataIndex: 'formName',
    title: '单据名称',
  }
];
</script>